package com.wlz.splitpackage;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * @author wlz
 * @date 2022-07-09  2:48 下午
 */
@Slf4j
public class PackageNettyClient {

    public static void main(String[] args) {

        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();

            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //向pipeline加入编码器
                            socketChannel.pipeline().addLast("encoder", new StringEncoder());
                            socketChannel.pipeline().addLast(new PackageNettyClientHandler());
                        }
                    });


            ChannelFuture cf = bootstrap.connect("127.0.0.1", 9000).sync();

            Channel channel = cf.channel();

            log.info(" =========   {}  ===========", channel.localAddress());


            for (int i = 0; i < 200; i++) {
                // 加入特殊分隔符分包 测试
//                channel.writeAndFlush("hello, wlz!" + "_");
//              // 加入回车换行分包 测试
//                channel.writeAndFlush("hello, wlz!" + "\n");
                // 加入 固定长度分包 测试
                channel.writeAndFlush("hello, wlz!");
            }

        } catch (Exception e) {
            log.error("PackageNettyClient error: {}", e);
        }finally {
            group.shutdownGracefully();
        }


    }
}
